package com.alibaba.citrus.ots.application.report.ability.repository.impl;

import com.alibaba.citrus.ots.application.report.ability.repository.BaseDataQueryRepository;
import com.alibaba.citrus.ots.application.report.ability.utils.PageRecordUtil;
import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineBatchQueryPlatforms2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetEmployeeByIdsAllRequest;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsAllRequest;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsAllResponse;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByOutCodes2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByOutCodes2Response;
import com.epoch.app.bcorder.model.dto.BatchQueryWarehouseByIds2Request;
import com.epoch.app.bcorder.model.dto.BatchQueryWarehouseByIdsRequest;
import com.epoch.app.bcorder.model.dto.CategorySDO;
import com.epoch.app.bcorder.model.dto.EmployeeSDO;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.PlatformSDO;
import com.epoch.app.bcorder.model.dto.QueryCategoryInfoByIdsRequest;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchCargoZoneListRequest;
import com.epoch.app.bcorder.model.dto.SearchCargoZoneListResponse;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.api.customersalescopequery.service.CustomerSaleScopeQueryService;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryAddressByConditionRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryByIdsRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryResponse;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.model.dto.BatchQueryCustomers2Request;
import com.epoch.app.crplatformenhance.model.dto.BatchQueryCustomers2Response;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.crplatformenhance.sdo.CustomerSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.model.dto.QueryCargoZoneById2Request;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInfoDTO;
import com.epoch.app.crunifiedinventory.model.dto.WmsSDO;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/11/25 20:29
 */
@Component
public class BaseDataQueryRepositoryImpl implements BaseDataQueryRepository {


    CustomerSaleScopeQueryService customerSaleScopeQueryService;

    @Resource
    BaseDataService baseDataService;
    @Resource
    CrPlatformEnhanceService otsPlatformEnhanceService;
    @Resource
    UnifiedInventoryService unifiedInventoryService;
    @Resource
    CustomerAddressService customerAddressService;
    @Resource
    CrUnifiedInventoryService otsUnifiedInventoryService;

    @Override
    public Map<String, OrganizationSDO> batchQueryOrganization(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, OrganizationSDO>();
        }
        BaselineGetOrganizationByIdsAllRequest request = new BaselineGetOrganizationByIdsAllRequest();
        request.setIds(distinctList(ids));
        BaselineGetOrganizationByIdsAllResponse result = baseDataService.baselineGetOrganizationByIdsAll(request);
        Map<String,OrganizationSDO> orgMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, OrganizationSDO>();
        return orgMap;
    }

    @Override
    public Map<String, OrganizationSDO> batchQueryOrganizationByOutCodes(List<String> outCodes) {
        if(CollectionUtils.isEmpty(outCodes)){
            return new HashMap<String, OrganizationSDO>();
        }
        BaselineGetOrganizationByOutCodes2Request request = new BaselineGetOrganizationByOutCodes2Request();
        request.setOutCodes(distinctList(outCodes));
        BaselineGetOrganizationByOutCodes2Response result = baseDataService.baselineGetOrganizationByOutCodes2(request);
        Map<String,OrganizationSDO> orgMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getOutCode, Function.identity(),(v1, v2)->v1)):new HashMap<String, OrganizationSDO>();
        return orgMap;
    }

    @Override
    public Map<String, EmployeeSDO> batchQueryEmplyee(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, EmployeeSDO>();
        }
        BaselineGetEmployeeByIdsAllRequest request = new BaselineGetEmployeeByIdsAllRequest();
        request.setIds(distinctList(ids));
        Result<List<EmployeeSDO>> result =  baseDataService.baselineGetEmployeeByIdsAll(request);
        Map<String,EmployeeSDO> empMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(EmployeeSDO::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, EmployeeSDO>();
        return empMap;
    }

    @Override
    public Map<String, CustomerSDO> batchQueryCustomer(List<String> codes) {
        if(CollectionUtils.isEmpty(codes)){
            return new HashMap<String, CustomerSDO>();
        }
        BatchQueryCustomers2Request request = new BatchQueryCustomers2Request();
        codes = distinctList(codes);
        int pageSize = 1000;
        int totalPage = codes.size()/pageSize;
        if (codes.size()%pageSize>0){
            totalPage++;
        }
        List<CustomerSDO> list = new ArrayList<>();
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo * pageSize;
            int end = pageNo+1 == totalPage ? codes.size(): start + pageSize;
            request.setCodes(codes.subList(start, end));
            BatchQueryCustomers2Response result = otsPlatformEnhanceService.batchQueryCustomers2(request);
            if(result!=null && CollectionUtils.isNotEmpty(result.getResult())){
                list.addAll(result.getResult());
            }
        }
        Map<String,CustomerSDO> custMap = CollectionUtils.isNotEmpty(list)?list.stream().collect(Collectors.toMap(CustomerSDO::getCode, Function.identity(),(v1, v2)->v1)):new HashMap<String, CustomerSDO>();
        return custMap;
    }

    @Override
    public Map<String, CustomerAddressSDO> batchQueryCustomerAddress(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, CustomerAddressSDO>();
        }
        BatchQueryByIdsRequest request = new BatchQueryByIdsRequest();
        ids = distinctList(ids);
        int pageSize = 1000;
        int totalPage = (ids.size() + pageSize - 1)/pageSize;
        List<CustomerAddressSDO> list = new ArrayList<>();
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo * pageSize;
            int end = pageNo+1 == totalPage ? ids.size(): start + pageSize;
            request.setIdList(ids.subList(start, end));
            Result<List<CustomerAddress>> result = customerAddressService.batchQueryByIds(request);
            List<CustomerAddressSDO> convertList = Nullable.stream(result.getResult()).map(x -> {
                CustomerAddressSDO bean = new CustomerAddressSDO();
                BeanUtils.copyProperties(x,bean);
                bean.setId(String.valueOf(x.getId()));
                return bean;
            }).collect(Collectors.toList());
            list.addAll(convertList);
        }
        Map<String,CustomerAddressSDO> addressMap = CollectionUtils.isNotEmpty(list)?list.stream().collect(Collectors.toMap(CustomerAddressSDO::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, CustomerAddressSDO>();
        return addressMap;
    }

    @Override
    public Map<String, CustomerAddressSDO> batchQueryCustomerAddressByCodes(List<String> codes) {
        if(CollectionUtils.isEmpty(codes)){
            return new HashMap<String, CustomerAddressSDO>();
        }
        BatchQueryRequest request = new BatchQueryRequest();
        codes = distinctList(codes);
        int pageSize = 300;
        int totalPage = (codes.size() + pageSize - 1)/pageSize;
        List<CustomerAddressSDO> list = new ArrayList<>();
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo * pageSize;
            int end = pageNo + 1 == totalPage ? codes.size() : start + pageSize;
            request.setAddressCodes(codes.subList(start, end));
            BatchQueryResponse result = customerAddressService.batchQuery(request);
            List<CustomerAddressSDO> convertList = Nullable.stream(result.getResult()).map(x -> {
                CustomerAddressSDO bean = new CustomerAddressSDO();
                BeanUtils.copyProperties(x,bean);
                bean.setId(String.valueOf(x.getId()));
                return bean;
            }).collect(Collectors.toList());
            list.addAll(convertList);
        }
        Map<String,CustomerAddressSDO> addressMap = CollectionUtils.isNotEmpty(list)?list.stream().collect(Collectors.toMap(x->x.getCustomerCode()+"#"+x.getAddressCode(), Function.identity(),(v1, v2)->v1)):new HashMap<String, CustomerAddressSDO>();
        return addressMap;
    }

//    @Override
//    public Map<String, CustomerAddressSDO> batchQueryCustomerAddress(List<String> ids) {
//        if(CollectionUtils.isEmpty(ids)){
//            return new HashMap<String, CustomerAddressSDO>();
//        }
//        BatchQueryByIdsRequest request = new BatchQueryByIdsRequest();
//        request.setIdList(distinctList(ids));
//        Result<List<CustomerAddress>> result = customerAddressService.batchQueryByIds(request);
//        List<CustomerAddressSDO> list = Nullable.stream(result.getResult()).map(x -> {
//            CustomerAddressSDO bean = new CustomerAddressSDO();
//            BeanUtils.copyProperties(x,bean);
//            bean.setId(String.valueOf(x.getId()));
//            return bean;
//        }).collect(Collectors.toList());
//        Map<String,CustomerAddressSDO> addressMap = CollectionUtils.isNotEmpty(list)?list.stream().collect(Collectors.toMap(CustomerAddressSDO::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, CustomerAddressSDO>();
//        return addressMap;
//    }

    @Override
    public Map<String, CustomerAddressSDO> batchQueryCustomerAddressByCondition(List<String> ids,String orgSalesOrganizationCode) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, CustomerAddressSDO>();
        }
        List<CustomerAddressSDO> result = new ArrayList<>();
        ids = distinctList(ids);
        int pageSize = 1000;
        int totalPage = (ids.size() + pageSize - 1)/pageSize;
        BatchQueryAddressByConditionRequest request = new BatchQueryAddressByConditionRequest();
        request.setOrgSalesOrganizationCodes(Lists.newArrayList(orgSalesOrganizationCode));
        request.setItemGroups(Lists.newArrayList("11"));
        request.setChannelCodes(Lists.newArrayList("20"));
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo * pageSize;
            int end = pageNo+1 == totalPage ? ids.size() : start + pageSize;
            List<String> tmpIds = ids.subList(start, end);
            List<String> customerCodes = tmpIds.stream().map(x -> {
                String[] array = x.split("#");
                return array[0];
            }).collect(Collectors.toList());
            List<String> addressCodes = tmpIds.stream().map(x -> {
                String[] array = x.split("#");
                return array[1];
            }).collect(Collectors.toList());
            request.setCustomerCodes(customerCodes);
            request.setAddressCodes(addressCodes);
            Result<List<CustomerAddress>> response = customerAddressService.batchQueryAddressByCondition(request);
            List<CustomerAddressSDO> convertList = Nullable.stream(response.getResult()).map(x -> {
                CustomerAddressSDO bean = new CustomerAddressSDO();
                BeanUtils.copyProperties(x,bean);
                bean.setId(String.valueOf(x.getId()));
                return bean;
            }).collect(Collectors.toList());
            result.addAll(convertList);
        }
        Map<String,CustomerAddressSDO> addressMap = CollectionUtils.isNotEmpty(result)?result.stream().collect(Collectors.toMap(x->x.getCustomerCode()+"#"+x.getAddressCode(), Function.identity(),(v1, v2)->v1)):new HashMap<String, CustomerAddressSDO>();
        return addressMap;
    }

    @Override
    public Map<String, ScItemSDO> batchQueryScItem(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, ScItemSDO>();
        }
        SearchScItemRequest request = new SearchScItemRequest();
        Map<String,Object> searchReqDTO = new HashMap<>();
        searchReqDTO.put("scItemIds",distinctList(ids));
        request.setSearchReqDTO(searchReqDTO);
        Result<List<ScItemSDO>> result =  baseDataService.searchScItem(request);
        Map<String,ScItemSDO> scItemMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(ScItemSDO::getScItemId, Function.identity(),(v1, v2)->v1)):new HashMap<String, ScItemSDO>();
        return scItemMap;
    }

    @Override
    @RepositoryInvoker
    public Map<String, ScItemSDO> batchQueryScItemDetail(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, ScItemSDO>();
        }
        List<ScItemSDO> result = new ArrayList<>();
        ids = distinctList(ids);
        int pageSize = 800;
        int totalPage = (ids.size() + pageSize - 1)/pageSize;
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo * pageSize;
            int end = pageNo+1 == totalPage ? ids.size() : start + pageSize;
            SearchScItemRequest request = new SearchScItemRequest();
            Map<String,Object> searchReqDTO = new HashMap<>();
            searchReqDTO.put("scItemIds",(ids.subList(start, end)));
            searchReqDTO.put("statusList",Lists.newArrayList("1","-1"));
            request.setSearchReqDTO(searchReqDTO);
            Result<List<ScItemSDO>> response =  baseDataService.searchScItem(request);
            List<ScItemSDO> scItemSDOList = response.getResult();
            if(CollectionUtils.isNotEmpty(scItemSDOList)){
                //填充类目
                List<String> categpryIds = scItemSDOList.stream().map(x -> {
                    return x.getLeafCategoryId();
                }).collect(Collectors.toList());
                categpryIds.removeAll(Collections.singleton(null));

                Map<String, CategorySDO> categorySDOMap = batchQueryCategory(categpryIds);
                List<String> rootCategpryIds = new ArrayList<>();
                for (ScItemSDO x:scItemSDOList) {
                    CategorySDO categorySDO = categorySDOMap.get(x.getLeafCategoryId());
                    if (categorySDO == null) {
                        continue;
                    }
                    //类目SDO父类目和根类目相同，则是一级类目
                    if (Objects.equals(categorySDO.getRootCategoryId(), categorySDO.getParentCategoryId())) {
                        x.setLeafCategoryId(null);
                        x.setLeafCategoryName(null);
                        x.setRootCategoryId(categorySDO.getCategoryId());
                        x.setRootCategoryName(categorySDO.getCategoryName());
                        //二级类目
                    } else {
                        x.setLeafCategoryId(categorySDO.getCategoryId());
                        x.setLeafCategoryName(categorySDO.getCategoryName());
                        x.setRootCategoryId(categorySDO.getParentCategoryId());
                        rootCategpryIds.add(categorySDO.getParentCategoryId());
                    }
                };
                if(CollectionUtils.isNotEmpty(rootCategpryIds)){
                    //填充一级类目名称
                    Map<String, CategorySDO> rootCategorySDOMap = batchQueryCategory(rootCategpryIds);
                    for (ScItemSDO x:scItemSDOList) {
                        if(StringUtil.isNotEmpty(x.getRootCategoryId()) && StringUtil.isBlank(x.getRootCategoryName()) ){
                            CategorySDO categorySDO = rootCategorySDOMap.get(x.getRootCategoryId());
                            if (categorySDO == null) {
                                continue;
                            }
                            x.setRootCategoryName(categorySDO.getCategoryName());
                        }
                    }
                }
                result.addAll(scItemSDOList);
            }
        }
        Map<String,ScItemSDO> scItemMap = CollectionUtils.isNotEmpty(result)?result.stream().collect(Collectors.toMap(ScItemSDO::getScItemId, Function.identity(),(v1, v2)->v1)):new HashMap<>();
        return scItemMap;
    }

    @Override
    public Map<String, CategorySDO> batchQueryCategory(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new HashMap<String, CategorySDO>();
        }
        QueryCategoryInfoByIdsRequest request = new QueryCategoryInfoByIdsRequest();
        request.setCategoryIdList(distinctList(ids));
        Result<List<CategorySDO>> result =  baseDataService.queryCategoryInfoByIds(request);
        Map<String,CategorySDO> categoryMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(CategorySDO::getCategoryId, Function.identity(),(v1, v2)->v1)):new HashMap<String, CategorySDO>();
        return categoryMap;
    }

    @Override
    public List<OrganizationSDO> batchQueryOrganizationGetList(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new ArrayList<OrganizationSDO>();
        }
        BaselineGetOrganizationByIdsAllRequest request = new BaselineGetOrganizationByIdsAllRequest();
        request.setIds(distinctList(ids));
        BaselineGetOrganizationByIdsAllResponse response = baseDataService.baselineGetOrganizationByIdsAll(request);
        List<OrganizationSDO> orgList = response.getResult();
        return orgList;
    }

    @Override
    public List<CategorySDO> batchQueryCategoryGetList(List<String> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return new ArrayList<CategorySDO>();
        }
        QueryCategoryInfoByIdsRequest request = new QueryCategoryInfoByIdsRequest();
        request.setCategoryIdList(distinctList(ids));
        Result<List<CategorySDO>> result = baseDataService.queryCategoryInfoByIds(request);
        return result.getResult();
    }

    @Override
    public Map<String, ScItemSDO> batchQueryScItemByOutCodes(List<String> outCodes) {
        SearchScItemRequest request = new SearchScItemRequest();
        Map<String,Object> searchReqDTO = new HashMap<>();
        searchReqDTO.put("outerIdList", distinctList(outCodes));
        request.setSearchReqDTO(searchReqDTO);
        Result<List<ScItemSDO>> result = baseDataService.searchScItem(request);
        Map<String,ScItemSDO> scItemMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(ScItemSDO::getOuterId, Function.identity(),(v1, v2)->v1)):new HashMap<String, ScItemSDO>();
        return scItemMap;
    }

    /**
     * 批量查询逻辑仓库信息
     * @param wmsIds
     * @return
     */
    @Override
    public Map<String, WmsSDO> batchQueryWmsByIds(List<String> wmsIds){
        Map<String,WmsSDO> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(wmsIds)){
            return map;
        }
        BatchQueryWarehouseByIdsRequest request = new BatchQueryWarehouseByIdsRequest();
        List<Integer> models = Lists.newArrayList(3);//1仓库档案，3逻辑仓
        request.setModelList(models);
        List<String> ids = distinctList(wmsIds);
        if(CollectionUtils.isEmpty(ids)){
            return map;
        }
        int pageSize = 1000;
        int totalPage = (ids.size() + pageSize - 1)/pageSize;
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo*pageSize;
            int end = pageNo+1 == totalPage ? ids.size() : start + pageSize;
            request.setWarehouseIds(ids.subList(start,end));
            Object object = unifiedInventoryService.batchQueryWarehouseByIds(request);
            if (object != null){
                JSONObject js = JSON.parseObject(JSON.toJSONString(object));
                if (js != null){
                    JSONArray array = js.getJSONArray("result");
                    if (array != null && array.size() > 0 ){
                        for (int i=0;i<array.size();i++){
                            JSONObject data = array.getJSONObject(i);
                            if (data != null){
                                WmsSDO wmsSDO = new WmsSDO();
                                String id = data.getString("id");
                                wmsSDO.setId(id);
                                wmsSDO.setName(data.getString("name"));
                                wmsSDO.setType(data.getString("type"));
                                wmsSDO.setWarehouseId(data.getString("warehouseId"));
                                JSONObject features = data.getJSONObject("features");
                                if (features != null){
                                    wmsSDO.setSapSalesOrgId(features.getString("sapSaleDepartment"));
                                    wmsSDO.setFactoryCode(features.getString("ecPlatform"));
                                }
                                map.put(id,wmsSDO);
                            }
                        }
                    }
                }
            }
        }
        return map;
    }

    @Override
    public Map<String, PlatformSDO> batchQueryPlatformsByIds(List<String> ids) {
        BaselineBatchQueryPlatforms2Request request = new BaselineBatchQueryPlatforms2Request();
        request.setPlatformIds(distinctList(ids));
        Result<List<PlatformSDO>> result = baseDataService.baselineBatchQueryPlatforms2(request);
        Map<String,PlatformSDO> platformsMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(PlatformSDO::getPlatformId, Function.identity(),(v1, v2)->v1)):new HashMap<String, PlatformSDO>();
        return platformsMap;
    }

    @Override
    public Map<String, PlatformSDO> batchQueryPlatformsByCodes(List<String> codes) {
        BaselineBatchQueryPlatforms2Request request = new BaselineBatchQueryPlatforms2Request();
        request.setPlatformCodes(distinctList(codes));
        Result<List<PlatformSDO>> result = baseDataService.baselineBatchQueryPlatforms2(request);
        Map<String,PlatformSDO> platformsMap = CollectionUtils.isNotEmpty(result.getResult())?result.getResult().stream().collect(Collectors.toMap(PlatformSDO::getPlatformCode, Function.identity(),(v1, v2)->v1)):new HashMap<String, PlatformSDO>();
        return platformsMap;
    }

    //取逻辑仓库
    @Override
    public Map<String, WarehouseInfoDTO> getLogicZoneInfo(List<String> warehouseAreaIds){
        if(CollectionUtils.isEmpty(warehouseAreaIds)){
            return new HashMap<String, WarehouseInfoDTO>();
        }
        QueryCargoZoneById2Request request = new QueryCargoZoneById2Request();
        List<String> ids = distinctList(warehouseAreaIds);
        int pageSize = 500;
        int totalPage = (ids.size() + pageSize - 1)/pageSize;
        List<WarehouseInfoDTO> result = new ArrayList<>();
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo * pageSize;
            int end = pageNo + 1 == totalPage ? ids.size() : start + pageSize;
            request.setCargoZoneIdList(ids.subList(start, end));
            Result<List<WarehouseInfoDTO>> response = otsUnifiedInventoryService.queryCargoZoneById2(request);
            if(response!=null && CollectionUtils.isNotEmpty(response.getResult())) {
                result.addAll(response.getResult());
            }
        }
        Map<String,WarehouseInfoDTO> warehouseMap = CollectionUtils.isNotEmpty(result)?result.stream().collect(Collectors.toMap(WarehouseInfoDTO::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, WarehouseInfoDTO>();
        return  warehouseMap;
    }

    //取门店终端
    @Override
    public Map<String, WarehouseInfo> getStoreInfo(List<String> warehouseAreaIds){
        if(CollectionUtils.isEmpty(warehouseAreaIds)){
            return new HashMap<String, WarehouseInfo>();
        }
        SearchCargoZoneListRequest request = new SearchCargoZoneListRequest();
        request.setWarehouseAreaIds(distinctList(warehouseAreaIds));
        request.setModel(6);
        request.setLimit(500);
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.resetPageParam();
        List<WarehouseInfo> result = new ArrayList<>();
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            request.setStart(pageUtil.getStart());
            SearchCargoZoneListResponse response = unifiedInventoryService.searchCargoZoneList(request);
            if(response!=null && CollectionUtils.isNotEmpty(response.getResult())) {
                result.addAll(response.getResult());
            }
            if(i == 1){
                pageUtil.setTotalPages(response!=null&&response.getSuccess()?response.getTotal():0);
            }
            pageUtil.turnPage();
        }
        Map<String,WarehouseInfo> warehouseMap = CollectionUtils.isNotEmpty(result)?result.stream().collect(Collectors.toMap(WarehouseInfo::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, WarehouseInfo>();
        return  warehouseMap;
    }

    //取仓库档案
    @Override
    public Map<String, WarehouseInfo> getWarehouseInfo(List<String> warehouseIds){
        if(CollectionUtils.isEmpty(warehouseIds)){
            return new HashMap<String, WarehouseInfo>();
        }
        BatchQueryWarehouseByIds2Request request = new BatchQueryWarehouseByIds2Request();
        request.setWarehouseIds(distinctList(warehouseIds));
        request.setModelList(Lists.newArrayList("1"));
        Result<List<WarehouseInfo>> response = unifiedInventoryService.batchQueryWarehouseByIds2(request);
        List<WarehouseInfo> result = response.getResult();
        //log.info("report_getWarehouseInfo_request={},response={}",JSON.toJSONString(request),JSON.toJSONString(result));
        Map<String,WarehouseInfo> warehouseMap = org.apache.commons.collections.CollectionUtils.isNotEmpty(result)?result.stream().collect(Collectors.toMap(WarehouseInfo::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, WarehouseInfo>();
        return warehouseMap;
    }


    //取工厂仓
    @Override
    public Map<String, WarehouseInfo> getFactoryLogicZoneInfo(){
        SearchCargoZoneListRequest request = new SearchCargoZoneListRequest();
        request.setModel(3);
        request.setType("5");
        request.setLimit(500);
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.resetPageParam();
        List<WarehouseInfo> result = new ArrayList<>();
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            request.setStart(pageUtil.getStart());
            SearchCargoZoneListResponse response = unifiedInventoryService.searchCargoZoneList(request);
            if(response!=null && CollectionUtils.isNotEmpty(response.getResult())){
                result.addAll(response.getResult());
            }
            if(i == 1){
                pageUtil.setTotalPages(response!=null&&response.getSuccess()?response.getTotal():0);
            }
            pageUtil.turnPage();
        }
        Map<String,WarehouseInfo> warehouseMap = CollectionUtils.isNotEmpty(result)?result.stream().collect(Collectors.toMap(WarehouseInfo::getId, Function.identity(),(v1, v2)->v1)):new HashMap<String, WarehouseInfo>();
        return  warehouseMap;
    }

//    @Override
//    public Integer convertScItemPCUnitNum(String scItemId, String unit) {
//        BaselineQueryRelationSpecByScItemIdRequest request = new BaselineQueryRelationSpecByScItemIdRequest();
//        request.setScItemId(scItemId);
//        BaselineQueryRelationSpecByScItemIdResponse response = baseDataService.baselineQueryRelationSpecByScItemId(request);
//        Integer convertNum = new Integer(1);
//        if (response != null && response.getResult() != null){
//            JSONObject result = JSON.parseObject(JSON.toJSONString(response.getResult()));
//            JSONArray specSDOList = result.getJSONArray("scItemSpecRelationAbilityDTOList");
//            if (specSDOList != null && specSDOList.size() > 0){
//                for (int i=0;i<specSDOList.size();i++){
//                    JSONObject sdo = specSDOList.getJSONObject(i);
//                    JSONObject features = sdo.getJSONObject("features");
//                    if(features != null && unit.equals(features.getString("unit"))){
//                        convertNum = sdo.getInteger("scItemNum");
//                       break;
//                    }
//                }
//            }
//        }
//        return convertNum;
//    }

    private List<String> distinctList(List<String> ids){
        ids = ids.stream().filter(x ->StringUtil.isNotEmpty(x)).collect(Collectors.toList());
        Set set = new HashSet();
        set.addAll(ids);
        ids.clear();
        ids.addAll(set);
        return ids;
    }
}
